<?php

declare (strict_types=1);
/**
 * @copyright 深圳市易果网络科技有限公司
 * @version 1.0.0
 * @link https://dayiguo.com
 */

namespace App\Service\User;


use App\Dao\AgentDao;
use App\Dao\AgentMoneyDao;
use App\Dao\PlatformDao;
use App\Dao\PlatformOrderDao;
use App\Dao\UserDao;
use App\Exception\CustomException;
use App\Job\ChannelJob;
use App\Kernel\Util\UserJwtInstance;
use App\Service\Service;


use Hyperf\DbConnection\Db;
use Hyperf\Snowflake\IdGeneratorInterface;
use Hyperf\Di\Annotation\Inject;

/**
 * 平台订单服务
 *
 * @author 张昊(2396675557@qq.com)
 * @package App\Service\User
 */
class PlatformOrderService  extends Service
{

    /**
     * 平台订单 DAO
     *
     * @Inject()
     * @var PlatformOrderDao
     */
    private $platform_order_dao;

    /**
     * 平台商品Dao
     * @Inject
     * @var PlatformDao
     */
    private $platform_dao;

    /**
     * @Inject
     *
     * @var PingPpService
     */
    private $ping_service;

    /**
     * @Inject
     * @var UserDao
     */
    private $user_dao;

    /**
     * @Inject
     * @var MoneyService
     */
    private $money_service;

    /**
     * @Inject
     * @var AgentDao
     */
    private $agent_dao;

    /**
     * @Inject
     * @var AgentMoneyDao
     */
    private $agent_money_dao;

    /**
     * @Inject
     * @var \App\Service\Agent\MoneyService
     */
    private $agent_monet_service;

    /**
     * 平台订单服务
     * @param int $id
     * @param string $channel
     * @return mixed
     */
    public function buy(int $id, string $channel)
    {
        $platform = $this->platform_dao->first(['id' => $id]);

        $order_no = (string)$this->container->get(IdGeneratorInterface::class)->generate();

        $data = [
            'status' => $this->platform_order_dao::STATUS_UNPAID,
            'user_id' => uid(),
            'order_no' => $order_no,
            'product_id' => $id,
            'amount' => $platform['price'],
            'pay_type' => $channel,
            'created_at' => time(),
            'updated_at' => time()
        ];


        $this->platform_order_dao->create($data);

        $result = [
            'amount' => $platform['price'],
            'order_no' => $order_no
        ];

        $payment = $this->ping_service->channel_pay($result, $channel,  $platform['name'], '渠道商购买');

        return $payment;
    }


    /**
     * 渠道商 分佣
     * @param string $order_no
     * @return mixed
     */
    public function channel(string $order_no)
    {
        $platform = $this->platform_order_dao->first([
            'order_no' => $order_no
        ]);

        if( $platform['status'] != 1 ) {
            $this->error();
        }

        $user = $this->user_dao->first($platform['user_id']);

        $parentFirst = $this->user_dao->first($user['parent_id']);

        if( $parentFirst && $parentFirst['group_id'] == 2 ) { //用户上级为渠道商

            $this->money_service->money_dao->create([
                'status' => $this->money_service->money_dao::STATUS_ENABLE,
                'user_id' => $parentFirst['id'],
                'lower_id' => $user['id'],
                'type' => $this->money_service->money_dao::INCOME_TYPE,
                'order_no' => $platform['order_no'],
                'source' => $this->money_service->money_dao::SOURCE_CHANNEL,
                'price_source' => 3,
                'num' => filterMoney($platform['amount'] * 0.25,4),
                'created_at' => time(),
                'goods_name' => $user['name'],
                'goods_pic' => $user['avatar'],
                'phone' => $user['phone'],
                'amount' => $platform['amount'],
            ]);
            $this->money_service->updateMoneyUserBalance($parentFirst['id']);
        } else if( $parentFirst && $parentFirst['group_id'] == 1 ) {//用户上级为会员 ，继续往上面查一级

            $superFirst = $this->user_dao->first($parentFirst['parent_id']);

            if( $superFirst && $superFirst['group_id'] == 2 ) { //用户上级为渠道商
                $this->money_service->money_dao->create([
                    'status' => $this->money_service->money_dao::STATUS_ENABLE,
                    'user_id' => $superFirst['id'],
                    'lower_id' => $user['id'],
                    'type' => $this->money_service->money_dao::INCOME_TYPE,
                    'order_no' => $platform['order_no'],
                    'source' => $this->money_service->money_dao::SOURCE_CHANNEL,
                    'price_source' => 3,
                    'num' => filterMoney($platform['amount'] * 0.25,4),
                    'created_at' => time(),
                    'goods_name' => $user['name'],
                    'goods_pic' => $user['avatar'],
                    'phone' => $user['phone'],
                    'amount' => $platform['amount'],
                ]);
                $this->money_service->updateMoneyUserBalance($parentFirst['id']);
            }
        }

        $areaAgent = $this->agent_dao->map([
            'location_id' => $user['district_id']
        ],false);

        if( !empty($areaAgent) && $areaAgent['identity'] == 1 ) {
            $this->agent_money_dao->create([
                'status' => 1,
                'agent_id' => $areaAgent['id'],
                'lower_id' => $user['id'],
                'type' => 1,
                'order_no' => $platform['order_no'],
                'source' => 1,
                'price_source' => 2,
                'num' => filterMoney($platform['amount'] * $areaAgent['channel_agent_money'],4),
                'goods_name' => $user['name'],
                'goods_pic' => $user['avatar'],
                'phone' => $user['phone'],
                'amount' => $platform['amount'],
                'created_at' => time(),
                'updated_at' => time(),
            ]);
            $this->agent_monet_service->updateMoneyAgentBalance($areaAgent['id']);
        }

        $cityAgent = $this->agent_dao->map([
            'location_id' => $user['city_id']
        ],false);

        if( !empty($cityAgent) && $cityAgent['identity'] == 2 ) {
            $this->agent_money_dao->create([
                'status' => 1,
                'agent_id' => $cityAgent['id'],
                'lower_id' => $user['id'],
                'type' => 1,
                'order_no' => $platform['order_no'],
                'source' => 2,
                'price_source' => 2,
                'num' => filterMoney($platform['amount'] * $cityAgent['channel_agent_money'],4),
                'goods_name' => $user['name'],
                'goods_pic' => $user['avatar'],
                'phone' => $user['phone'],
                'amount' => $platform['amount'],
                'created_at' => time(),
                'updated_at' => time(),
            ]);
            $this->agent_monet_service->updateMoneyAgentBalance($cityAgent['id']);
        }

        $partnerAgent = $this->agent_dao->map([
            'id' => $areaAgent['inviter_id']
        ],false);

        if( !empty($partnerAgent) && $partnerAgent['identity'] == 3  ) { //分公司
            $this->agent_money_dao->create([
                'status' => 1,
                'agent_id' => $partnerAgent['id'],
                'lower_id' => $user['id'],
                'area_id' => $areaAgent['id'],
                'type' => 1,
                'order_no' => $platform['order_no'],
                'source' => 4,
                'price_source' => 2,
                'num' => filterMoney($platform['amount'] * $partnerAgent['channel_agent_money'],4),
                'goods_name' => $user['name'],
                'goods_pic' => $user['avatar'],
                'phone' => $user['phone'],
                'amount' => $platform['amount'],
                'created_at' => time(),
                'updated_at' => time(),
            ]);
            $this->agent_monet_service->updateMoneyAgentBalance($partnerAgent['id']);
        } else if( !empty($partnerAgent) && $partnerAgent['identity'] == 4 ) {//合伙人
            $this->agent_money_dao->create([
                'status' => 1,
                'agent_id' => $partnerAgent['id'],
                'lower_id' => $user['id'],
                'type' => 1,
                'order_no' => $platform['order_no'],
                'source' => 4,
                'price_source' => 2,
                'num' => filterMoney($platform['amount'] * $partnerAgent['channel_agent_money'],4),
                'goods_name' => $user['name'],
                'goods_pic' => $user['avatar'],
                'phone' => $user['phone'],
                'amount' => $platform['amount'],
                'created_at' => time(),
                'updated_at' => time(),
            ]);
            $this->agent_monet_service->updateMoneyAgentBalance($partnerAgent['id']);
            $branchAgent = $this->agent_dao->map([
                'id' => $partnerAgent['inviter_id']
            ],false); //合伙人查询分公司

            $branchAgentAmount = $branchAgent['channel_agent_money'] - $partnerAgent['channel_agent_money'];

            $this->agent_money_dao->create([
                'status' => 1,
                'agent_id' => $branchAgent['id'],
                'lower_id' => $user['id'],
                'partner_id' => $partnerAgent['id'],
                'type' => 1,
                'order_no' => $platform['order_no'],
                'source' => 3,
                'price_source' => 2,
                'num' => filterMoney($platform['amount'] * $branchAgentAmount,4),
                'goods_name' => $user['name'],
                'goods_pic' => $user['avatar'],
                'phone' => $user['phone'],
                'amount' => $platform['amount'],
                'created_at' => time(),
                'updated_at' => time(),
            ]);

            $this->agent_monet_service->updateMoneyAgentBalance($branchAgent['id']);
        }

    }


    /**
     * ping++ 渠道商回调
     *
     * @param array $params
     * @return mixed
     */
    public function pingNotify($params)
    {
        $where['status'] = $this->platform_order_dao::STATUS_UNPAID;
        $where['order_no'] = substr($params['order_no'],7);
        $platform = $this->platform_order_dao->first($where);
        if( !$platform ) {
            return false;
        }
        $platform->trade_id = $params['transaction_no'];
        $platform->status = $this->platform_order_dao::STATUS_PAID;
        $platform->updated_at = time();
        if($platform->save()) {
            $user = $this->user_dao->first($platform['user_id']);
            $user->group_id = 2;
            $user->save();
            $this->driver->push(new ChannelJob( $platform->order_no ));
        }
    }

}